<?php

// +----------------------------------------------------------------------
// | RXThinkCMF框架 [ RXThinkCMF ]
// +----------------------------------------------------------------------
// | 版权所有 2017~2020 南京RXThinkCMF研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.rxthink.cn
// +----------------------------------------------------------------------
// | Author: 牧羊人 <1175401194@qq.com>
// +----------------------------------------------------------------------

namespace app\api\controller;
header('Access-Control-Allow-Origin: *');


use app\common\library\Men;
use app\common\library\wxpay\FzweixinPay;
use PhpMqtt\Client\ConnectionSettings;
use PhpMqtt\Client\MqttClient;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\facade\Log;
use think\Response;


/**
 * H5控制器基类
 *
 * @author 牧羊人
 * @since 2020-04-21
 */
class Wap
{
    // 模型
    protected $model;
    // 服务


    protected $service;
    // 校验
    protected $validate;

    public $token;


    /**
     * 交互
     * @param $beginTime1
     * @param $endTime1
     * @param $beginTime2
     * @param $endTime2
     * @return bool
     */
    public function is_time_cross($beginTime1 = '', $endTime1 = '', $beginTime2 = '', $endTime2 = '')
    {
        // 1681655400    1681669800     1681669800  1681673400

        $status = $beginTime2 - $beginTime1;
        if ($status > 0) {
            $status2 = $beginTime2 - $endTime1;
            if ($status2 >= 0) {
                return false;
            } else {
                return true;
            }
        } else {
            $status2 = $endTime2 - $beginTime1;
            if ($status2 > 0) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 开门
     * @param $door_list
     * @param $admin_id
     * @param $user_id
     * @return bool
     * @throws \think\db\exception\DbException
     */
    public static function open($door_list, $admin_id, $user_id)
    {
        $access_token = '';
        if (isset($door_list['expires_in']) && isset($door_list['access_token'])) {
            if ($door_list['expires_in'] < time()) {

                $appId = $door_list['appId'];
                $apiKey = $door_list['appkey'];
                $res = Men::token($appId, $apiKey);

                if (!isset($res['access_token'])) {

                    $arr['code'] = 0;
                    $arr['message'] = '开锁失败,请联系客服1';
                    Response::create($arr, 'json')->send();
                    exit();
                }
                $access_token = $res['access_token'];
                $update['access_token'] = $res['access_token'];
                $update['expires_in'] = strtotime($res['expires_in']);
                Db::name('customer_set_cabinet')->where(['appId' => $door_list['appId']])->update($update);
            } else {

                $access_token = $door_list['access_token'];
            }
        } else {
            $appId = $door_list['appId'];
            $apiKey = $door_list['appkey'];
            $res = Men::token($appId, $apiKey);
            if (!isset($res['access_token'])) {
                $arr['code'] = 101;
                $arr['message'] = '开锁失败,请联系客服1';
                Response::create($arr, 'json')->send();
                exit();
            }
            $access_token = $res['access_token'];
            $update['access_token'] = $res['access_token'];
            $update['expires_in'] = strtotime($res['expires_in']);
            Db::name('customer_set_cabinet')->where(['appId' => $door_list['appId']])->update($update);
        }
        //看门
        $return = Men::unlock($access_token, $door_list['equipment_id']);

        if (isset($return['code']) && $return['code'] == 0 && $return['msg'] == 'success') {
            return true;

        } else {
            // 记录信息
            $doorList = array(
                'admin_id' => $admin_id,
                'create_time' => time(),
                'user_id' => $user_id,
                'status' => 2,
                'data' => json_encode($return),
                'content' => json_encode($door_list),
            );
            Db::name('mini_admin_lamp_list')->insert($doorList);
            return $return;
        }
    }

    /**
     * 开门
     * @param $door_list
     * @param $admin_id
     * @param $user_id
     * @return bool
     * @throws \think\db\exception\DbException
     */
    public static function newopen($deviceCode, $type)
    {
        header("Content-type: text/html; charset=utf-8");
        $encryptionStr = strtoupper(md5('deviceCode=' . $deviceCode));
        $apiurl = "https://qsg.wuminginfo.com/api/device/generateTask?encryptionStr=" . $encryptionStr . "&deviceCode=" . $deviceCode . "&type=" . $type;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch, CURLOPT_URL, $apiurl);
        $data = curl_exec($ch);
        return json_decode($data, true);
    }

    public  static function mqttopenone($door_id='RFA1A76C6C', $time){

        $server = '47.96.100.201';
        $port     = 1883;
        $clientId = rand(5, 15);
        $username = 'emqx_user';
        $password = null;
        $clean_session = false;
        $connectionSettings  = new ConnectionSettings();
        $connectionSettings
            ->setUsername($username)
            ->setPassword($password)
            ->setKeepAliveInterval(60);
        $mqtt = new MqttClient($server, $port, $clientId);
        $mqtt->connect($connectionSettings, $clean_session);
        $mqtt->subscribe('CIOT/2000/DEVICE/'.$door_id, function ($topic, $message) use ($mqtt,$time) {
            $message=json_decode($message,true);
            if($message['Body']['Type']==0 and $message['Body']['SubType']==0){
              //  $result =json_encode(['message' => $time==0?'断电成功':'开锁成功', 'code' => 200, 'success' => true]) ;
                printf( 200);exit();
            }else{
                $result =json_encode(['message' =>$time==0?'断电失败':'开锁失败', 'code' => $message['Header']['code'], 'success' => false]) ;
                printf( $message['Header']['code']);exit();
            }

            $mqtt->interrupt();
        }, 0);
        $payload = ['Header' => ['Code' => '1004', 'Time' => time()*1000, 'Sign' => 'lvzaina'],
            'Body' => ['MsgId' => time(), 'Cmd' => 'Order','ID'=>1,'Delay'=>$time*60,'Type'=>0,'Lock'=>0]];
        //向客户端发送消息
        $mqtt->publish(
        // topic
            'CIOT/2000/HOST/'.$door_id,
            // payload
            json_encode($payload),
            // qos
            0,
            // retain
            false
        );
        $mqtt->loop(true);
    }

    /**
     * 授权
     * @param $door_list
     * @param $admin_id
     * @param $user_id
     * @param $add_time
     * @param $end_time
     * @throws \think\db\exception\DbException
     */
    public function code($door_list, $admin_id, $user_id, $add_time, $end_time)
    {


        $access_token = '';
        if (isset($door_list['expires_in']) && isset($door_list['access_token'])) {

            if ($door_list['expires_in'] < time()) {


                $appId = $door_list['appId'];
                $apiKey = $door_list['appkey'];
                $res = Men::token($appId, $apiKey);


                if (!isset($res['access_token'])) {
                    $arr['code'] = 0;
                    $arr['message'] = '开锁失败,请联系客服1';
                    Response::create($arr, 'json')->send();
                    exit();
                }
                $access_token = $res['access_token'];
                $update['access_token'] = $res['access_token'];
                $update['expires_in'] = strtotime($res['expires_in']);
                Db::name('customer_set_cabinet')->where(['appId' => $door_list['appId']])->update($update);

            } else {

                $access_token = $door_list['access_token'];
            }
        } else {
            $appId = $door_list['appId'];
            $apiKey = $door_list['appkey'];
            $res = Men::token($appId, $apiKey);

            if (!isset($res['access_token'])) {
                $arr['code'] = 0;
                $arr['message'] = '开锁失败,请联系客服1';
                Response::create($arr, 'json')->send();
                exit();
            }
            $access_token = $res['access_token'];
            $update['access_token'] = $res['access_token'];
            $update['expires_in'] = strtotime($res['expires_in']);
            Db::name('customer_set_cabinet')->where(['appId' => $door_list['appId']])->update($update);
        }

        $return = $this->shcode($access_token, $door_list['door_id'], $add_time, $end_time);
        require "../vendor/phpqrcode/phpqrcode.php";

        $qRcode = new \QRcode();
        $urlstr = $return['data'];

        //生成二维码图片
        $errorCorrectionLevel = 'L';    //容错级别
        $matrixPointSize = 5;            //生成图片大小
        $img = mt_rand(0, 9999) . uniqid() . mt_rand(0, 9999) . mt_rand(0, 9999) . '.png';
        $file_path = 'qrcode/' . date('Ymd') . '/';
        $path = root_path() . 'public/qrcode/' . $file_path;
        if (!file_exists($path)) {
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($path, 0777, true);
        }
        $filename = $path . $img;
        $qRcode::png($urlstr, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
        $QR = $filename;                //已经生成的原始二维码图片文件
        $QR = imagecreatefromstring(file_get_contents($QR));
        //保存图片,销毁图形，释放内存
        if (!file_exists($filename)) {
            imagepng($QR, $filename);
            imagedestroy($QR);
        } else {
            imagedestroy($QR);
        }

        $data[] = array();

        return $file_path . $img;


    }


    /**
     * 发送语音
     * @param $door_list
     * @param $admin_id
     * @param $user_id
     * @param $voice
     * @return bool|mixed|void
     */
    public
    static function openvoice($door_list, $voice)
    {


        if (!$door_list['equipment_id']) {

            return true;
        }
        $access_token = '';
        if (isset($door_list['expires_in']) && isset($door_list['access_token'])) {
            if ($door_list['expires_in'] < time()) {

                $appId = $door_list['appId'];
                $apiKey = $door_list['appkey'];
                $res = Men::token($appId, $apiKey);

                if (!isset($res['access_token'])) {

                    $arr['code'] = 0;
                    $arr['message'] = '开锁失败,请联系客服1';
                    Response::create($arr, 'json')->send();
                    exit();
                }
                $access_token = $res['access_token'];
                $update['access_token'] = $res['access_token'];
                $update['expires_in'] = strtotime($res['expires_in']);
                Db::name('customer_set_cabinet')->where(['appId' => $door_list['appId']])->update($update);
            } else {

                $access_token = $door_list['access_token'];
            }
        } else {
            $appId = $door_list['appId'];
            $apiKey = $door_list['appkey'];
            $res = Men::token($appId, $apiKey);
            if (!isset($res['access_token'])) {
                $arr['code'] = 101;
                $arr['message'] = '开锁失败,请联系客服1';
                Response::create($arr, 'json')->send();
                exit();
            }
            $access_token = $res['access_token'];
            $update['access_token'] = $res['access_token'];
            $update['expires_in'] = strtotime($res['expires_in']);
            Db::name('customer_set_cabinet')->where(['appId' => $door_list['appId']])->update($update);
        }
        //看门


        $return = Men::unlockvoice($access_token, $door_list['equipment_id'], $voice);


        return true;

    }

    /**
     * 查询对应的门禁
     * @param $course_id
     * @param $user
     * @param $order_id
     * @return bool
     */
    public function doorlist($course_id, $user, $order_id, $face_image)
    {

        $course = Db::name('customer_course')->where('id', $course_id)->find();


        switch ($course['type']) {
            case 1:
                $doolist = Db::name('customer_door_list')->where('id', $course['door_id'])->find();
                $appkey = Db::name('customer_set_cabinet')->where('store_id', $course['store_id'])->find();

                if ($doolist['type'] == 3) {
                    // 注册人脸


                    if (isset($appkey['expires_in']) && isset($appkey['access_token'])) {
                        if ($appkey['expires_in'] < time()) {


                            $appId = $appkey['appId'];
                            $apiKey = $appkey['appkey'];
                            $res = Men::token($appId, $apiKey);

                            if (!isset($res['access_token'])) {

                                $arr['code'] = 0;
                                $arr['message'] = '授权错误,请联系客服';
                                Response::create($arr, 'json')->send();
                                exit();
                            }
                            $access_token = $res['access_token'];
                            $update['access_token'] = $res['access_token'];
                            $update['expires_in'] = strtotime($res['expires_in']);
                            Db::name('customer_set_cabinet')->where(['appId' => $appkey['appId']])->update($update);
                        } else {
                            $access_token = $appkey['access_token'];
                        }
                    } else {
                        $appId = $appkey['appId'];
                        $apiKey = $appkey['appkey'];
                        $res = Men::token($appId, $apiKey);
                        if (!isset($res['access_token'])) {
                            $arr['code'] = 101;
                            $arr['message'] = '授权错误,请联系客服';
                            Response::create($arr, 'json')->send();
                            exit();
                        }
                        $access_token = $res['access_token'];
                        $update['access_token'] = $res['access_token'];
                        $update['expires_in'] = strtotime($res['expires_in']);
                        Db::name('customer_set_cabinet')->where(['appId' => $appkey['appId']])->update($update);
                    }

                    $info = $this->equipinfo($user, $access_token);


                    if ($info['code'] != 100101) {

                        $info = $this->equipment($user, $access_token);

                    }

                    $data = $this->registerTbload($access_token, $user['mobile'], $doolist['equipment_id'], $face_image);


                    if ($data['code'] != 1) {
                        return '0';
                    }
                    $this->binding($access_token, $user['mobile'], $doolist['equipment_id']);
                    $this->xia($access_token, $user['mobile'], $doolist['equipment_id']);

                    $this->rexie($access_token, $user['mobile'], $doolist['equipment_id']);
                }
                break;
            case 2:
                $orderlist = Db::name('mini_store_seat_store')->where('order_id', $order_id)->select();
                foreach ($orderlist as $i => $v) {
                    $store = Db::name('customer_store')->where('id', $v['seat_id'])->find();

                    $doolist = Db::name('customer_door_list')->where('id', $store['door_id'])->find();
                    $appkey = Db::name('customer_set_cabinet')->where('store_id', $course['store_id'])->find();

                    if ($doolist['type'] == 3) {
                        // 注册人脸


                        if (isset($appkey['expires_in']) && isset($appkey['access_token'])) {
                            if ($appkey['expires_in'] < time()) {


                                $appId = $appkey['appId'];
                                $apiKey = $appkey['appkey'];
                                $res = Men::token($appId, $apiKey);

                                if (!isset($res['access_token'])) {

                                    $arr['code'] = 0;
                                    $arr['message'] = '授权错误,请联系客服';
                                    Response::create($arr, 'json')->send();
                                    exit();
                                }
                                $access_token = $res['access_token'];
                                $update['access_token'] = $res['access_token'];
                                $update['expires_in'] = strtotime($res['expires_in']);
                                Db::name('customer_set_cabinet')->where(['appId' => $appkey['appId']])->update($update);
                            } else {
                                $access_token = $appkey['access_token'];
                            }
                        } else {
                            $appId = $appkey['appId'];
                            $apiKey = $appkey['appkey'];
                            $res = Men::token($appId, $apiKey);
                            if (!isset($res['access_token'])) {
                                $arr['code'] = 101;
                                $arr['message'] = '授权错误,请联系客服';
                                Response::create($arr, 'json')->send();
                                exit();
                            }
                            $access_token = $res['access_token'];
                            $update['access_token'] = $res['access_token'];
                            $update['expires_in'] = strtotime($res['expires_in']);
                            Db::name('customer_set_cabinet')->where(['appId' => $appkey['appId']])->update($update);
                        }

                        $info = $this->equipinfo($user, $access_token);

                        if ($info['code'] != 100101) {
                            $this->equipment($user, $access_token);
                        }
                        $data = $this->registerTbload($access_token, $user['mobile'], $doolist['equipment_id'], $face_image);


                        if ($data['code'] != 1) {
                            return '0';
                        }
                        $this->binding($access_token, $user['mobile'], $doolist['equipment_id']);
                        $this->xia($access_token, $user['mobile'], $doolist['equipment_id']);

                        $this->rexie($access_token, $user['mobile'], $doolist['equipment_id']);

                    }
                }
                break;
            case 3:
                $doolist = Db::name('customer_door_list')->where('id', $course['door_id'])->find();
                if ($doolist['type'] == 3) {
                    // 注册人脸

                    $appkey = Db::name('customer_set_cabinet')->where('store_id', $course['store_id'])->find();
                    $doolist['access_token'] = $appkey['access_token'];
                    if (isset($door_list['expires_in']) && isset($door_list['access_token'])) {
                        if ($door_list['expires_in'] < time()) {

                            $appId = $door_list['appId'];
                            $apiKey = $door_list['appkey'];
                            $res = Men::token($appId, $apiKey);

                            if (!isset($res['access_token'])) {

                                $arr['code'] = 0;
                                $arr['message'] = '授权错误,请联系客服';
                                Response::create($arr, 'json')->send();
                                exit();
                            }
                            $access_token = $res['access_token'];
                            $update['access_token'] = $res['access_token'];
                            $update['expires_in'] = strtotime($res['expires_in']);
                            Db::name('customer_set_cabinet')->where(['appId' => $door_list['appId']])->update($update);
                        } else {

                            $access_token = $door_list['access_token'];
                        }
                    } else {
                        $appId = $door_list['appId'];
                        $apiKey = $door_list['appkey'];
                        $res = Men::token($appId, $apiKey);
                        if (!isset($res['access_token'])) {
                            $arr['code'] = 101;
                            $arr['message'] = '授权错误,请联系客服';
                            Response::create($arr, 'json')->send();
                            exit();
                        }
                        $access_token = $res['access_token'];
                        $update['access_token'] = $res['access_token'];
                        $update['expires_in'] = strtotime($res['expires_in']);
                        Db::name('customer_set_cabinet')->where(['appId' => $door_list['appId']])->update($update);
                    }

                    $info = $this->equipinfo($user, $access_token);
                    if ($info['code'] != 100101) {
                        $this->equipment($user, $access_token);
                    }
                    $banguser = $this->registe($access_token, $user['mobile'], $doolist['equipment_id']);
                    if ($banguser['code'] != 100101) {
                        $this->registerTbload($access_token, $user['mobile'], $doolist['equipment_id'], $face_image);

                        $this->binding($access_token, $user['mobile'], $doolist['equipment_id']);
                        $this->xia($access_token, $user['mobile'], $doolist['equipment_id']);

                        $this->rexie($access_token, $user['mobile'], $doolist['equipment_id']);

                    }

                }
                break;
        }
    }


    /**
     * 通知
     * @param $wxapp_id
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function token($wxapp_id)
    {
        $wxapp = Db::name('mini_match')->where(['id' => $wxapp_id])->find();

        if ($wxapp['token'] == "") {
            $appid = $wxapp['app_id'];
            $app_secret = $wxapp['key'];

            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$app_secret}";
            $token = $this->curl($url, 'get', '');


            // 记录并保存
            $data = array(
                'token' => $token['access_token'],
                'end_token_time' => time() + 7200
            );

            Db::name('mini_match')->where(['id' => $wxapp_id])->update($data);

            return $token['access_token'];
        } elseif ($wxapp['end_token_time'] < time()) {

            $appid = $wxapp['app_id'];
            $app_secret = $wxapp['key'];
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$app_secret}";

            $token = $this->curl($url, 'get', '');
            // 记录并保存
            $data = array(
                'token' => $token['access_token'],
                'end_token_time' => time() + 7200
            );

            if (Db::name('mini_match')->where(['id' => $wxapp_id])->update($data)) {
                return $token['access_token'];
            }


        } else {
            return $wxapp['token'];
        }

    }

    /**
     * 请求
     * @param $url
     * @param $method
     * @param $params
     * @return mixed
     */
    public function curl($url, $method, $params)
    {

        //初始化CURL句柄
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);//设置请求的URL
        #curl_setopt($curl, CURLOPT_HEADER, false);// 不要http header 加快效率
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //设为TRUE把curl_exec()结果转化为字串，而不是直接输出
        //SSL验证
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);    // https请求时要设置为false 不验证证书和hosts  FALSE 禁止 cURL 验证对等证书（peer's certificate）, 自cURL 7.10开始默认为 TRUE。从 cURL 7.10开始默认绑定安装。
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);//检查服务器SSL证书中是否存在一个公用名(common name)。

        $header[] = "Content-Type:application/json;charset=utf-8";
        if (!empty($header)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);//设置 HTTP 头字段的数组。格式： array('Content-type: text/plain', 'Content-length: 100')
        }
        //请求时间
        $timeout = 30;
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);//设置连接等待时间

        //不同请求方法的数据提交
        switch ($method) {
            case "GET" :
                curl_setopt($curl, CURLOPT_HTTPGET, true);//TRUE 时会设置 HTTP 的 method 为 GET，由于默认是 GET，所以只有 method 被修改时才需要这个选项。
                break;
            case "POST":
                if (is_array($params)) {
                    $params = json_encode($params, 320);
                }
                #curl_setopt($curl, CURLOPT_POST,true);//TRUE 时会发送 POST 请求，类型为：application/x-www-form-urlencoded，是 HTML 表单提交时最常见的一种。
                #curl_setopt($curl, CURLOPT_NOBODY, true);//TRUE 时将不输出 BODY 部分。同时 Mehtod 变成了 HEAD。修改为 FALSE 时不会变成 GET。
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");//HTTP 请求时，使用自定义的 Method 来代替"GET"或"HEAD"。对 "DELETE" 或者其他更隐蔽的 HTTP 请求有用。 有效值如 "GET"，"POST"，"CONNECT"等等；
                //设置提交的信息
                curl_setopt($curl, CURLOPT_POSTFIELDS, $params);//全部数据使用HTTP协议中的 "POST" 操作来发送。
                break;
            case "PUT" :
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params, 320));
                break;
            case "DELETE":
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
                curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
                break;
        }

        $data = curl_exec($curl);//执行预定义的CURL


        curl_getinfo($curl, CURLINFO_HTTP_CODE);//获取http返回值,最后一个收到的HTTP代码
        curl_close($curl);//关闭cURL会话
        $res = json_decode($data, true);


        return $res;
    }


    /**
     * 获取时期
     * @return array
     */
    public function time()
    {
        $hours_add_time = array(
            'hours_add_time' => [
                1 => '00',
                2 => '01',
                3 => '02',
                4 => '03',
                5 => '04',
                6 => '05',
                7 => '06',
                8 => '07',
                9 => '08',
                10 => '09',
                11 => '10',
                12 => '11',
                13 => '12',
                14 => '13',
                15 => '14',
                16 => '15',
                17 => '16',
                18 => '17',
                19 => '18',
                20 => '19',
                21 => '20',
                22 => '21',
                23 => '22',
                24 => '23',

            ],
            'hours_end_time' => [
                1 => '00',
                2 => '01',
                3 => '02',
                4 => '03',
                5 => '04',
                6 => '05',
                7 => '06',
                8 => '07',
                9 => '08',
                10 => '09',
                11 => '10',
                12 => '11',
                13 => '12',
                14 => '13',
                15 => '14',
                16 => '15',
                17 => '16',
                18 => '17',
                19 => '18',
                20 => '19',
                21 => '20',
                22 => '21',
                23 => '22',
                24 => '23',
                25 => '24',

            ],
            'time_add' => [
                0 => '00',
                1 => '01',
                2 => '02',
                3 => '03',
                4 => '04',
                5 => '05',
                6 => '06',
                7 => '07',
                8 => '08',
                9 => '09',
                10 => '10',
                11 => '11',
                12 => '12',
                13 => '13',
                14 => '14',
                15 => '15',
                16 => '16',
                17 => '17',
                18 => '18',
                19 => '19',
                20 => '20',
                21 => '21',
                22 => '22',
                23 => '23',
                24 => '24',
                25 => '25',
                26 => '26',
                27 => '27',
                28 => '28',
                29 => '29',
                30 => '30',
                31 => '31',
                32 => '32',
                33 => '33',
                34 => '34',
                35 => '35',
                36 => '36',
                37 => '37',
                38 => '38',
                39 => '39',
                40 => '40',
                41 => '41',
                42 => '42',
                43 => '43',
                44 => '44',
                45 => '45',
                46 => '46',
                47 => '47',
                48 => '48',
                49 => '49',
                50 => '50',
                51 => '51',
                52 => '52',
                53 => '53',
                54 => '54',
                55 => '55',
                56 => '56',
                57 => '57',
                58 => '58',
                59 => '59',
            ],
        );

        return $hours_add_time;
    }


    public function timedata()
    {
        $hours_add_time = array(
            'hours_add_time' => [
                1 => '00',
                2 => '01',
                3 => '02',
                4 => '03',
                5 => '04',
                6 => '05',
                7 => '06',
                8 => '07',
                9 => '08',
                10 => '09',
                11 => '10',
                12 => '11',
                13 => '12',
                14 => '13',
                15 => '14',
                16 => '15',
                17 => '16',
                18 => '17',
                19 => '18',
                20 => '19',
                21 => '20',
                22 => '21',
                23 => '22',
                24 => '23',

            ],
            'hours_end_time' => [
                1 => '00',
                2 => '01',
                3 => '02',
                4 => '03',
                5 => '04',
                6 => '05',
                7 => '06',
                8 => '07',
                9 => '08',
                10 => '09',
                11 => '10',
                12 => '11',
                13 => '12',
                14 => '13',
                15 => '14',
                16 => '15',
                17 => '16',
                18 => '17',
                19 => '18',
                20 => '19',
                21 => '20',
                22 => '21',
                23 => '22',
                24 => '23',
                25 => '24',

            ],
            'time_add' => [
                0 => '00',
                1 => '01',
                2 => '02',
                3 => '03',
                4 => '04',
                5 => '05',
                6 => '06',
                7 => '07',
                8 => '08',
                9 => '09',
                10 => '10',
                11 => '11',
                12 => '12',
                13 => '13',
                14 => '14',
                15 => '15',
                16 => '16',
                17 => '17',
                18 => '18',
                19 => '19',
                20 => '20',
                21 => '21',
                22 => '22',
                23 => '23',
                24 => '24',
                25 => '25',
                26 => '26',
                27 => '27',
                28 => '28',
                29 => '29',
                30 => '30',
                31 => '31',
                32 => '32',
                33 => '33',
                34 => '34',
                35 => '35',
                36 => '36',
                37 => '37',
                38 => '38',
                39 => '39',
                40 => '40',
                41 => '41',
                42 => '42',
                43 => '43',
                44 => '44',
                45 => '45',
                46 => '46',
                47 => '47',
                48 => '48',
                49 => '49',
                50 => '50',
                51 => '51',
                52 => '52',
                53 => '53',
                54 => '54',
                55 => '55',
                56 => '56',
                57 => '57',
                58 => '58',
                59 => '59',
            ],
        );

        return $hours_add_time;
    }

    /**
     * 获取周期
     * @param $time
     * @param int $i
     * @return string
     */
    public function getTimeWeeks($time)
    {
        $weekarray = array("周日", "周一", "周二", "周三", "周四", "周五", "周六");


        return $weekarray[date("w", $time)];
    }

    /**
     * 生成订单号
     * @return string
     */
    public function orderOn()
    {
        $order_id_main = date('YmdHi') . rand(10000000, 99999999);
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        $osn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);

        return $osn;
    }

    //get请求
    public static function getHttp($url)
    {
        $ch = curl_init();
        //设置传输地址
        curl_setopt($ch, CURLOPT_URL, $url);
        //设置以文件流形式输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_ENCODING, '');
        //接收返回数据
        $data = curl_exec($ch);
        curl_close($ch);
        $jsonInfo = json_decode($data, true);

        return $jsonInfo;
    }


    /**
     * 开灯
     * @param $door_list
     * @param $admin_id
     * @param $user_id
     * @param int $status
     * @return bool|void
     */
    public static function opens($door_list, $status = 0)
    {

        $access_token = '';
        if (isset($door_list['expires_in']) && isset($door_list['access_token'])) {
            if ($door_list['expires_in'] < time()) {

                $appId = $door_list['appId'];
                $apiKey = $door_list['appkey'];
                $res = Men::token($appId, $apiKey);
                if (!isset($res['access_token'])) {

                    $arr['code'] = 0;
                    $arr['message'] = '开灯失败,请联系客服2';
                    Response::create($arr, 'json')->send();
                    exit();
                }
                $access_token = $res['access_token'];
                $update['access_token'] = $res['access_token'];
                $update['expires_in'] = strtotime($res['expires_in']);
                Db::name('customer_set_cabinet')->where(['appId' => $door_list['appId']])->update($update);
            } else {

                $access_token = $door_list['access_token'];
            }
        } else {

            $appId = $door_list['appId'];
            $apiKey = $door_list['appkey'];
            $res = Men::token($appId, $apiKey);


            if (!isset($res['access_token'])) {
                $arr['code'] = 0;
                $arr['message'] = '开锁失败,请联系客服1';
                Response::create($arr, 'json')->send();
                exit();
            }
            $access_token = $res['access_token'];
            $update['access_token'] = $res['access_token'];
            $update['expires_in'] = strtotime($res['expires_in']);
            Db::name('customer_set_cabinet')->where(['appId' => $door_list['appId']])->update($update);
        }
        //开灯


        $return = Men::unlockdook($access_token, $door_list['equipment_id'], $status, 01);


        if (isset($return['code']) && $return['code'] == 0 && $return['msg'] == 'success') {

            return true;

        } else {
            if (isset($return['code'])) {
                Log::record('失败' . $return['code']);
            } else {
                Log::record('物联网请求失败');
            }
            return false;
        }

    }

    /**
     * 自动关灯
     * @param $door_list
     * @param $admin_id
     * @param $user_id
     * @param int $status
     * @return bool|void
     */
    public static function openend($door_list, $admin_id, $user_id, $status = 0, $lockid = 0)
    {

        $access_token = '';
        if (isset($door_list['expires_in']) && isset($door_list['access_token'])) {
            if ($door_list['expires_in'] < time()) {

                $appId = $door_list['appId'];
                $apiKey = $door_list['appkey'];
                $res = Men::token($appId, $apiKey);
                if (!isset($res['access_token'])) {

                    $arr['code'] = 0;
                    $arr['message'] = '开灯失败,请联系客服2';
                    Response::create($arr, 'json')->send();
                    exit();
                }
                $access_token = $res['access_token'];
                $update['access_token'] = $res['access_token'];
                $update['expires_in'] = strtotime($res['expires_in']);
                Db::name('customer_set_cabinet')->where(['appId' => $door_list['appId']])->update($update);
            } else {

                $access_token = $door_list['access_token'];
            }
        } else {

            $appId = $door_list['appId'];
            $apiKey = $door_list['appkey'];
            $res = Men::token($appId, $apiKey);


            if (!isset($res['access_token'])) {
                $arr['code'] = 0;
                $arr['message'] = '开锁失败,请联系客服1';
                Response::create($arr, 'json')->send();
                exit();
            }
            $access_token = $res['access_token'];
            $update['access_token'] = $res['access_token'];
            $update['expires_in'] = strtotime($res['expires_in']);
            Db::name('customer_set_cabinet')->where(['appId' => $door_list['appId']])->update($update);
        }
        //开灯

        $return = Men::unlockdook($access_token, $door_list['equipment_id'], $status, $lockid);


        if (isset($return['code']) && $return['code'] == 0 && $return['msg'] == 'success') {

            return true;

        } else {
            if (isset($return['code'])) {
                Log::record('失败' . $return['code']);
            } else {
                Log::record('物联网请求失败');
            }

            // 记录信息
            $doorList = array(
                'admin_id' => $admin_id,
                'create_time' => time(),
                'user_id' => $user_id,
                'status' => 2,
                'data' => json_encode($return),
                'content' => json_encode($door_list),
            );
            Db::name('mini_admin_lamp_list')->insert($doorList);
            return false;
        }
    }


    /**
     *求两个已知经纬度之间的距离,单位为千米
     * @param lng1,lng2 经度
     * @param lat1,lat2 纬度
     * @return float 距离，单位千米
     **/
    public static function distance($lng1, $lat1, $lng2, $lat2)//根据经纬度计算距离
    {
        //将角度转为弧度
        $radLat1 = deg2rad($lat1);

        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);

        $radLng2 = deg2rad($lng2);

        $a = $radLat1 - $radLat2;//两纬度之差,纬度<90
        $b = $radLng1 - $radLng2;//两经度之差纬度<180

        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;
        return $s;
    }

    /**
     * @return string
     */
    public static function createToken()
    {
        $randChar = static::getRandChar(32);
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        $tokenSalt = '63KAGxtT7bjATzwP';
        return md5($randChar . $timestamp . $tokenSalt);
    }


    /**
     * 验证token
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkToken()
    {

        $header = \request()->header();
        $post = \request()->param();
        $token = $header['token'];
        if ($token) {
            $where = array();
            $where['token'] = $token;


            $user_list = DB::name('member')->where($where)->find();

            if (!$user_list) {
                $arr['code'] = 401;
                $arr['message'] = '请先登录';
                Response::create($arr, 'json')->send();
                exit();
            }

            $this->user = $user_list;
            $this->token = $token;

            return $user_list;
        } else {
            $arr['code'] = 401;
            $arr['message'] = '请先登录';
            Response::create($arr, 'json')->send();
            exit();
        }
    }


    /**
     * @content 返回任意字符串
     */
    public static function getRandChar($length)
    {
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol) - 1;

        for ($i = 0;
             $i < $length;
             $i++) {
            $str .= $strPol[rand(0, $max)];
        }

        return $str;
    }


    /**
     * 推销分成
     * @param $room_id
     * @param $price
     * @param $type
     * @param $content
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */


    public function distribution($room_id, $price1, $types, $content, $order_id, $order_on, $transaction_id)
    {
        $room = Db::name('mini_room_list')->where('id', $room_id)->find();
        $wxapp = Db::name('mini_match')->where('id', 1)->find();

        $weixinpay = new FzweixinPay($wxapp['app_id'], '', $wxapp['mch_id'], $wxapp['api_key'], $order_on, $body = '', $total_fee = '', $type = '', $room['sub_mch_id']);

        $info = Db::name('mini_room_list_distribution')->where('store_id', $room_id)->find();

        $p = 0;
        $d['1_id'] = 0;
        $d['2_id'] = 0;
        $d['3_id'] = 0;
//有上级
        if ($info) {
            $daiprice = 0;
            $bi = Db::name('mimi_fees')->where('id', 1)->find();
            switch ($room['type']) {
                //  加盟店
                case 1:
                    if ($info['direct_id'] > 0) {

                        $da1 = Db::name('mini_room_list')->where('id', $info['direct_id'])->where('mark', 1)->find();

                        if ($da1) {
                            // 直推商家收益
                            $data['price'] = $price1 * ($bi['yi_price'] / 100);
                            $data['store_id'] = $da1['id'];
                            $data['direct_id'] = $room_id;
                            $data['type'] = $type;
                            $data['content'] = $content . '1';
                            $data['order_id'] = $order_id;
                            $data['create_time'] = time();
                            if (empty(Db::name('distribution_price')->where(['store_id' => $da1['id'],
                                'order_id' => $order_id, 'type' => $type, 'direct_id' => $room_id, 'is_long' => 0])->find())) {
                                Db::name('distribution_price')->insert($data);
                            }

                            $d['1_id'] = $da1['id'];
                            $p = $bi['yi_price'];

                            $dal['direct_price'] = $da1['num_price'] + $data['price'];
                            $dal['num_price'] = $da1['num_price'] + $data['price'];


                            $dal['price'] = $da1['price'] + $data['price'];

                            $daiprice = $daiprice + $data['price'];
                            Db::name('mini_room_list')->where('id', $da1['id'])->update($dal);

                            // 2级商家收益
                            if ($da1['direct_id'] > 0) {
                                $da2 = Db::name('mini_room_list')->where('id', $da1['direct_id'])->where('mark', 1)->find();
//大于6家
                                if ($da2['direct_num'] > 6) {

                                    $data = array();
                                    $d['2_id'] = $da2['id'];
                                    $data['price'] = $price1 * ($bi['er_price'] / 100);
                                    $p = $p + $bi['er_price'];

                                    $data['store_id'] = $da2['id'];
                                    $data['direct_id'] = $room_id;
                                    $data['second_id'] = $info['direct_id'];
                                    $data['type'] = $type;
                                    $data['content'] = $content . '2';
                                    $data['order_id'] = $order_id;
                                    $data['create_time'] = time();

                                    if (empty(Db::name('distribution_price')->where(['store_id' => $da2['id'],
                                        'order_id' => $order_id, 'type' => $type, 'direct_id' => $da2['id'], 'is_long' => 0])->find())) {
                                        Db::name('distribution_price')->insert($data);
                                    }


                                    $da2['second_price'] = $da2['second_price'] + $data['price'];
                                    $da2['num_price'] = $da2['num_price'] + $data['price'];
                                    $da2['price'] = $da2['price'] + $data['price'];

                                    $daiprice = $daiprice + $data['price'];
                                    Db::name('mini_room_list')->where('id', $da2['id'])->update($da2);


                                }
                                // 3级商家收益
                                if ($da2['direct_id'] > 0) {
                                    $da3 = Db::name('mini_room_list')->where('id', $da2['direct_id'])->where('mark', 1)->find();
                                    if ($da3['direct_num'] > 6) {
                                        // 查询2级商家推荐人数
                                        $num = Db::name('mini_room_list')->where('direct_id', $da3['id'])->where('direct_num', '>', 14)->count();

                                        if ($num > 1) {
                                            $num = $da3['direct_num'] + $da3['second_num'] + $da3['leve_num'];
                                            if ($num > 41) {
                                                $d['3_id'] = $da3['id'];
                                                $data = array();
                                                $p = $p + $bi['sn_price'];
                                                $data['price'] = $price1 * ($bi['sn_price'] / 100);
                                                $data['store_id'] = $da3['id'];
                                                $data['direct_id'] = $room_id;
                                                $data['second_id'] = $da1['id'];
                                                $data['leve_id'] = $da2['id'];
                                                $data['type'] = $type;
                                                $data['content'] = $content . '3';
                                                $data['order_id'] = $order_id;
                                                if (empty(Db::name('distribution_price')->where(['store_id' => $da3['id'],
                                                    'order_id' => $order_id, 'type' => $type, 'direct_id' => $da3['id'], 'is_long' => 0])->find())) {
                                                    Db::name('distribution_price')->insert($data);
                                                }

                                                $da3['leve_price'] = $da3['leve_price'] + $data['price'];
                                                $da3['num_price'] = $da3['num_price'] + $data['price'];
                                                $da3['price'] = $da3['price'] + $data['price'];

                                                $daiprice = $daiprice + $data['price'];
                                                Db::name('mini_room_list')->where('id', $da3['id'])->update($da3);


                                            }
                                        }
                                    }
                                }
                            }
                        }

                    }
                    $info = Db::name('mini_room_list')->where('id', $room_id)->find();
                    //查询该区域第一家
                    $da = Db::name('mini_room_list')->where('id', '<>', $room_id)->where('district_code', $info['district_code'])->where('is_long', 1)->find();
                    if ($da) {
                        $data = array();
                        $data['price'] = $price1 * ($bi['qu_price'] / 100);
                        $data['is_long'] = $da['id'];
                        $data['direct_id'] = $room_id;
                        $p = $p + $bi['qu_price'];
                        $data['type'] = $type;
                        $data['content'] = $content . 'qu';
                        $data['order_id'] = $order_id;
                        $data['create_time'] = time();

                        if (empty(Db::name('distribution_price')->where(['direct_id' => $room_id,
                            'order_id' => $order_id, 'type' => $type, 'direct_id' =>$room_id, 'is_long' => $da['id']])->find())) {
                            Db::name('distribution_price')->insert($data);
                        }

                        $da['price'] = $da['price'] + $data['price'];

                        $daiprice = $daiprice + $data['price'];
                        Db::name('mini_room_list')->where('id', $da['id'])->update($da);


                    }
                    // 更新商家金额
                    $price = $price1 - ($price1 * ($bi['corporation'] / 100));

                    $info = Db::name('mini_room_list')->where('id', $room_id)->find();


                    $info['price'] = $info['price'] + $price;

                    if ($room['sub_mch_id'] == null) {
                        Db::name('mini_room_list')->where('id', $room_id)->update($info);
                    }


//平台
                    $price = $price1 * (($bi['corporation'] - $p) * 0.01);
                    $da = array(
                        'type' => $type,
                        'content' => $content,
                        'order_id' => $order_id,
                        'store_id' => $room_id,
                        'price' => $price,
                        'create_time' => time(),
                        'de_price' => $price1,
                        'num' => ($bi['corporation'] - $p) * 0.01,
                        'level_id' => $d['3_id'],
                        'second_id' => $d['2_id'],
                        'direct_id' => $d['1_id'],

                    );


                    if (empty(Db::name('admin_price')->where(['store_id' => $room_id,
                        'order_id' => $order_id, 'type' => $type, 'direct_id' => $d['1_id']])->find())) {
                        Db::name('admin_price')->insert($da);
                    }
//分给平台
                    $weixinpay->addreceiver($wxapp['mch_id'], $room['sub_mch_id'], $wxapp['app_id'], $wxapp['app_id'], $receivers = ['type' => 'MERCHANT_ID', 'account' => $wxapp['mch_id'], 'name' => '闲来娱乐', 'relation_type' => 'SERVICE_PROVIDER']);

                   $fzorder =   $weixinpay->fzorder($wxapp['mch_id'], $room['sub_mch_id'], $wxapp['app_id'], $wxapp['app_id'], $transaction_id, $order_on, $receivers = [['type' => 'MERCHANT_ID', 'account' => $wxapp['mch_id'], 'amount' =>(int) floor($price1 * $bi['corporation']), 'description' => '平台抽成']]);


                    break;
                //联营
                case 2:
                    if ($info['direct_id'] > 0) {
                        $da1 = Db::name('mini_room_list')->where('id', $info['direct_id'])->where('mark', 1)->find();
                        if ($da1) {
                            // 直推商家收益
                            $data['price'] = $price1 * $bi['li_yi_price'] * 0.01;
                            $data['store_id'] = $da1['id'];
                            $data['direct_id'] = $room_id;
                            $data['type'] = $type;
                            $data['content'] = $content;
                            $data['order_id'] = $order_id;

                            if (empty(Db::name('distribution_price')->where(['store_id' => $da1['id'],
                                'order_id' => $order_id, 'type' => $type, 'direct_id' => $room_id, 'is_long' => 0])->find())) {
                                Db::name('distribution_price')->insert($data);
                            }
                            $d['1_id'] = $da1['id'];
                            $p = $bi['li_yi_price'];
                            // 更新商家直推金额
                            $dal['direct_price'] = $da1['num_price'] + $data['price'];
                            $dal['num_price'] = $da1['num_price'] + $data['price'];
                            $dal['price'] = $da1['price'] + $data['price'];
                            $daiprice = $daiprice + $data['price'];
                            Db::name('mini_room_list')->where('id', $da1['id'])->update($dal);


                            // 2级商家收益
                            if ($da1['direct_id'] > 0) {
                                $da2 = Db::name('mini_room_list')->where('id', $da1['direct_id'])->where('mark', 1)->find();

                                if ($da2['direct_num'] > 6) {

                                    $data = array();
                                    $d['2_id'] = $da2['id'];
                                    $data['price'] = $price1 * $bi['li_er_price'] * 0.01;
                                    $p = $p + $bi['li_er_price'];

                                    $data['store_id'] = $da2['id'];
                                    $data['direct_id'] = $room_id;
                                    $data['second_id'] = $info['direct_id'];
                                    $data['type'] = $type;
                                    $data['content'] = $content;
                                    $data['order_id'] = $order_id;

                                    if (empty(Db::name('distribution_price')->where(['store_id' => $da2['id'],
                                        'order_id' => $order_id, 'type' => $type, 'direct_id' => $room_id, 'is_long' => 0])->find())) {
                                        Db::name('distribution_price')->insert($data);
                                    }
                                    // 更新一级推金额

                                    $da2['second_price'] = $da2['second_price'] + $data['price'];
                                    $da2['num_price'] = $da2['num_price'] + $data['price'];
                                    $da2['price'] = $da2['price'] + $data['price'];


                                    $daiprice = $daiprice + $data['price'];
                                    Db::name('mini_room_list')->where('id', $da2['id'])->update($da2);

                                }
                                // 3级商家收益
                                if ($da2['direct_id'] > 0) {
                                    $da3 = Db::name('mini_room_list')->where('id', $da2['direct_id'])->where('mark', 1)->find();
                                    if ($da3['direct_num'] > 6) {
                                        // 查询2级商家推荐人数
                                        $num = Db::name('mini_room_list')->where('direct_id', $da3['id'])->where('direct_num', '>', 14)->count();

                                        if ($num > 1) {
                                            $num = $da3['direct_num'] + $da3['second_num'] + $da3['leve_num'];
                                            if ($num > 41) {
                                                $d['3_id'] = $da3['id'];
                                                $data = array();
                                                $p = $p + $bi['li_sn_price'];
                                                $data['price'] = $price1 * $bi['li_sn_price'] * 0.01;

                                                $data['store_id'] = $da3['id'];
                                                $data['direct_id'] = $room_id;
                                                $data['second_id'] = $da1['id'];
                                                $data['leve_id'] = $da2['id'];
                                                $data['type'] = $type;
                                                $data['content'] = $content;
                                                $data['order_id'] = $order_id;
                                                if (empty(Db::name('distribution_price')->where(['store_id' => $da3['id'],
                                                    'order_id' => $order_id, 'type' => $type, 'direct_id' => $room_id, 'is_long' => 0])->find())) {
                                                    Db::name('distribution_price')->insert($data);
                                                }
                                                // 更新二级推金额


                                                $da3['leve_price'] = $da1['leve_price'] + $data['price'];
                                                $da3['num_price'] = $da1['num_price'] + $data['price'];
                                                $da3['price'] = $da3['price'] + $data['price'];

                                                $daiprice = $daiprice + $data['price'];
                                                Db::name('mini_room_list')->where('id', $da3['id'])->update($da3);

                                            }
                                        }
                                    }
                                }
                            }
                        }

                    }
                    $info = Db::name('mini_room_list')->where('id', $room_id)->find();
                    $da = Db::name('mini_room_list')->where('id', '<>', $room_id)->where('district_code', $info['district_code'])->where('is_long', 1)->find();
                    if ($da) {
                        $data = array();
                        $data['price'] = $price1 * $bi['li_qu_price'] * 0.01;
                        $data['is_long'] = $da['id'];
                        $data['direct_id'] = $room_id;
                        $p = $p + $bi['li_qu_price'];
                        $data['type'] = $type;
                        $data['content'] = $content;
                        $data['order_id'] = $order_id;

                        if (empty(Db::name('distribution_price')->where(['direct_id' => $room_id,
                            'order_id' => $order_id, 'type' => $type, 'is_long' => $da['id']])->find())) {
                            Db::name('distribution_price')->insert($data);
                        }
                        $da['price'] = $da['price'] + $data['price'];
                        $daiprice = $daiprice + $data['price'];
                        Db::name('mini_room_list')->where('id', $da['id'])->update($da);

                    }
                    // 更新商家金额
                    $price = $price1 - ($price1 * $bi['li_corporation']);
                    $info = Db::name('mini_room_list')->where('id', $room_id)->find();
                    $info['price'] = $info['price'] + $price;
                    if ($room['sub_mch_id'] == null) {
                        Db::name('mini_room_list')->where('id', $room_id)->update($info);
                    }
                    $price = $price1 * ($bi['li_corporation'] - $p) * 0.01;
                    $da = array(
                        'type' => $type,
                        'content' => $content,
                        'order_id' => $order_id,
                        'store_id' => $room_id,
                        'price' => $price,
                        'create_time' => time(),
                        'de_price' => $price1,
                        'num' => $bi['corporation'] - $p,
                        'level_id' => $d['3_id'],
                        'second_id' => $d['2_id'],
                        'direct_id' => $d['1_id'],

                    );


                    if (empty(Db::name('admin_price')->where(['store_id' => $room_id,
                        'order_id' => $order_id, 'type' => $type, 'direct_id' => $d['1_id']])->find())) {
                        Db::name('admin_price')->insert($da);
                    }
                    $weixinpay->addreceiver($wxapp['mch_id'], $room['sub_mch_id'], $wxapp['app_id'], $wxapp['app_id'], $receivers = ['type' => 'MERCHANT_ID', 'account' => $wxapp['mch_id'], 'name' => '闲来娱乐', 'relation_type' => 'SERVICE_PROVIDER']);

                   $fzorder =   $weixinpay->fzorder($wxapp['mch_id'], $room['sub_mch_id'], $wxapp['app_id'], $wxapp['app_id'], $transaction_id, $order_on, $receivers = [['type' => 'MERCHANT_ID', 'account' => $wxapp['mch_id'], 'amount' =>(int) floor($price1 * $bi['li_corporation']), 'description' => '平台抽成']]);
//分给自己
                    break;
                case 3:
//直营

                    if ($info['direct_id'] > 0) {
                        $da1 = Db::name('mini_room_list')->where('id', $info['direct_id'])->where('mark', 1)->find();
                        if ($da1) {
                            // 直推商家收益
                            $data['price'] = $price1 * $bi['zi_yi_price'] * 0.01;
                            $data['store_id'] = $da1['id'];
                            $data['direct_id'] = $room_id;
                            $data['type'] = $type;
                            $data['content'] = $content;
                            $data['order_id'] = $order_id;


                            if (empty(Db::name('distribution_price')->where(['store_id' => $da1['id'],
                                'order_id' => $order_id, 'type' => $type, 'is_long' => 0])->find())) {
                                Db::name('distribution_price')->insert($data);
                            }
                            $d['1_id'] = $da1['id'];
                            $p = $bi['zi_yi_price'];
                            // 更新商家直推金额


                            $dal['direct_price'] = $da1['num_price'] + $data['price'];
                            $dal['num_price'] = $da1['num_price'] + $data['price'];
                            $dal['price'] = $da1['price'] + $data['price'];
                            Db::name('mini_room_list')->where('id', $da1['id'])->update($dal);

                            // 2级商家收益
                            if ($da1['direct_id'] > 0) {
                                $da2 = Db::name('mini_room_list')->where('id', $da1['direct_id'])->where('mark', 1)->find();

                                if ($da2['direct_num'] > 6) {

                                    $data = array();
                                    $d['2_id'] = $da2['id'];
                                    $data['price'] = $price1 * $bi['zi_er_price'] * 0.01;
                                    $p = $p + $bi['zi_er_price'];

                                    $data['store_id'] = $da2['id'];
                                    $data['direct_id'] = $room_id;
                                    $data['second_id'] = $info['direct_id'];
                                    $data['type'] = $type;
                                    $data['content'] = $content;
                                    $data['order_id'] = $order_id;
                                    if (empty(Db::name('distribution_price')->where(['store_id' => $da2['id'],
                                        'order_id' => $order_id, 'type' => $type, 'direct_id' => $room_id, 'is_long' => 0])->find())) {
                                        Db::name('distribution_price')->insert($data);
                                    }
                                    // 更新一级推金额


                                    $da2['second_price'] = $da2['second_price'] + $data['price'];
                                    $da2['num_price'] = $da2['num_price'] + $data['price'];
                                    $da2['price'] = $da2['price'] + $data['price'];
                                    Db::name('mini_room_list')->where('id', $da2['id'])->update($da2);


                                }
                                // 3级商家收益
                                if ($da2['direct_id'] > 0) {
                                    $da3 = Db::name('mini_room_list')->where('id', $da2['direct_id'])->where('mark', 1)->find();
                                    if ($da3['direct_num'] > 6) {
                                        // 查询2级商家推荐人数
                                        $num = Db::name('mini_room_list')->where('direct_id', $da3['id'])->where('direct_num', '>', 14)->count();

                                        if ($num > 1) {
                                            $num = $da3['direct_num'] + $da3['second_num'] + $da3['leve_num'];
                                            if ($num > 41) {
                                                $d['3_id'] = $da3['id'];
                                                $data = array();
                                                $p = $p + $bi['zi_sn_price'];
                                                $data['price'] = $price1 * $bi['zi_sn_price'] * 0.01;

                                                $data['store_id'] = $da3['id'];
                                                $data['direct_id'] = $room_id;
                                                $data['second_id'] = $da1['id'];
                                                $data['leve_id'] = $da2['id'];
                                                $data['type'] = $type;
                                                $data['content'] = $content;
                                                $data['order_id'] = $order_id;
                                                if (empty(Db::name('distribution_price')->where(['store_id' => $da3['id'],
                                                    'order_id' => $order_id, 'type' => $type, 'direct_id' => $room_id, 'is_long' => 0])->find())) {
                                                    Db::name('distribution_price')->insert($data);
                                                }


                                                $da3['leve_price'] = $da1['leve_price'] + $data['price'];
                                                $da3['num_price'] = $da1['num_price'] + $data['price'];
                                                $da3['price'] = $da3['price'] + $data['price'];

                                                Db::name('mini_room_list')->where('id', $da3['id'])->update($da3);

                                            }
                                        }
                                    }
                                }
                            }
                        }

                    }
                    $info = Db::name('mini_room_list')->where('id', $room_id)->find();
                    $da = Db::name('mini_room_list')->where('id', '<>', $room_id)->where('district_code', $info['district_code'])->where('is_long', 1)->find();

                    if ($da) {
                        $data = array();
                        $data['price'] = $price1 * $bi['zi_qu_price'] * 0.01;
                        $data['is_long'] = $da['id'];
                        $data['direct_id'] = $room_id;
                        $p = $p + $bi['zi_qu_price'];
                        $data['type'] = $type;
                        $data['content'] = $content;
                        $data['order_id'] = $order_id;


                        if (empty(Db::name('distribution_price')->where([
                            'order_id' => $order_id, 'type' => $type, 'direct_id' => $room_id, 'is_long' => $da['id']])->find())) {
                            Db::name('distribution_price')->insert($data);
                        }
                        $da['price'] = $da['price'] + $data['price'];

                        Db::name('mini_room_list')->where('id', $da['id'])->update($da);

                    }
                    // 更新商家金额
                    $price = $price1 * ($bi['zi_corporation'] - $p) * 0.01;

                    $da = array(
                        'type' => $type,
                        'content' => $content,
                        'order_id' => $order_id,
                        'store_id' => $room_id,
                        'price' => $price,
                        'create_time' => time(),
                        'de_price' => $price1,
                        'num' => $bi['corporation'] - $p,
                        'level_id' => $d['3_id'],
                        'second_id' => $d['2_id'],
                        'direct_id' => $d['1_id'],

                    );

                    if (empty(Db::name('admin_price')->where([
                        'order_id' => $order_id, 'type' => $type, 'direct_id' => $d['1_id']])->find())) {
                        Db::name('admin_price')->insert($da);
                    }
                    break;
                case 4:
                    $info = Db::name('mini_room_list')->where('id', $room_id)->find();
                    $da = Db::name('mini_room_list')->where('id', '<>', $room_id)->where('district_code', $info['district_code'])->where('is_long', 1)->find();
                    if ($da) {
                        $data = array();
                        $data['price'] = $price1 * $bi['w_yu_price'] * 0.01;
                        $data['is_long'] = $da['id'];
                        $data['direct_id'] = $room_id;
                        $p = $p + $bi['w_yu_price'];
                        $data['type'] = $type;
                        $data['content'] = $content;
                        $data['order_id'] = $order_id;

                        if (empty(Db::name('distribution_price')->where([
                            'order_id' => $order_id, 'type' => $type, 'direct_id' => $room_id, 'is_long' => $da['id']])->find())) {
                            Db::name('distribution_price')->insert($data);
                        }

                        $da['price'] = $da['price'] + $data['price'];
                        Db::name('mini_room_list')->where('id', $da['id'])->update($da);

                    }

                    // 更新商家金额
                    $price = $price1 - ($price1 * ($bi['w_corporation'] * 0.01));
                    $info = Db::name('mini_room_list')->where('id', $room_id)->find();

                    $info['price'] = $info['price'] + $price;
                    if ($room['sub_mch_id'] == null) {
                        Db::name('mini_room_list')->where('id', $room_id)->update($info);
                    }
                    $price = $price1 * ($bi['w_corporation'] - $p) * 0.01;
                    $da = array(
                        'type' => $type,
                        'content' => $content,
                        'order_id' => $order_id,
                        'store_id' => $room_id,
                        'price' => $price,
                        'create_time' => time(),
                        'de_price' => $price1,
                        'num' => $bi['corporation'] - $p,
                        'level_id' => $d['3_id'],
                        'second_id' => $d['2_id'],
                        'direct_id' => $d['1_id'],

                    );
                    if (empty(Db::name('admin_price')->where([
                        'order_id' => $order_id, 'type' => $type, 'store_id' => $room_id, 'direct_id' => $d['1_id']])->find())) {
                        Db::name('admin_price')->insert($da);
                    }
                    $weixinpay->addreceiver($wxapp['mch_id'], $room['sub_mch_id'], $wxapp['app_id'], $wxapp['app_id'], $receivers = ['type' => 'MERCHANT_ID', 'account' => $wxapp['mch_id'], 'name' => '闲来娱乐', 'relation_type' => 'DISTRIBUTOR']);
                    $fzorder =   $weixinpay->fzorder($wxapp['mch_id'], $room['sub_mch_id'], $wxapp['app_id'], $wxapp['app_id'], $transaction_id, $order_on, $receivers = [['type' => 'MERCHANT_ID', 'account' => $wxapp['mch_id'], 'amount' =>(int) floor($price1 * $bi['w_corporation']), 'description' => '平台抽成']]);



                    break;
            }
//分给自己


//            $arr=[1=>$bi['corporation'],2=>$bi['li_corporation'],3=>$bi['zi_corporation'],4=>$bi['w_corporation']];
//            $ratio=  $arr[$room['type']]/100;
//            $receiversarr[]= ['type' => 'MERCHANT_ID', 'account' => $wxapp['mch_id'], 'amount' =>(int) (round($price1*(1-$ratio) , 2) * 100), 'description' => '店铺应得'];
//            if($room['type']!==3){
//                $weixinpay->addreceiver($wxapp['mch_id'], $room['sub_mch_id'], $wxapp['app_id'], $wxapp['app_id'], $receivers = ['type' => 'MERCHANT_ID', 'account' => $room['sub_mch_id'], 'name' => $room['sub_mch_name'], 'relation_type' => 'DISTRIBUTOR']);
//
//                $weixinpay->fzorder($wxapp['mch_id'], $room['sub_mch_id'], $wxapp['app_id'], $wxapp['app_id'], $transaction_id, $order_on,$receiversarr);
//
//            }

            $endfz = $weixinpay->endfz($wxapp['mch_id'], $room['sub_mch_id'], $wxapp['app_id'], $wxapp['app_id'], $transaction_id, $order_on);

        } else {
            //没有上级
            if ($room['sub_mch_id'] == null) {
                $dal['price'] = $price1;
                Db::name('mini_room_list')->where('id', $room_id)->update($dal);
            }

            $endfz = $weixinpay->endfz($wxapp['mch_id'], $room['sub_mch_id'], $wxapp['app_id'], $wxapp['app_id'], $transaction_id, $order_on);

        }
        if($room['type']!==3){

          if( $fzorder =='SUCCESS'){
              if ($types == 1) {
                  Db::name('customer_order')->where('order_on', $order_on)->where('if_fz', 1)->update(['if_fz' => 2]);

              } elseif ($types == 2) {
                  Db::name('customer_renewal_order')->where('order_on', $order_on)->where('if_fz', 1)->update(['if_fz' => 2]);

              } elseif ($types == 4) {
                  Db::name('customer_recharge_order')->where('order_on', $order_on)->where('if_fz', 1)->update(['if_fz' => 2]);
              }elseif ($types == 8) {
                  Db::name('customer_coupon_order')->where('order_on', $order_on)->where('if_fz', 1)->update(['if_fz' => 2]);
              }

          }



        }else{
            if ($types == 1) {
                Db::name('customer_order')->where('order_on', $order_on)->where('if_fz', 1)->update(['if_fz' => 2]);

            } elseif ($types == 2) {
                Db::name('customer_renewal_order')->where('order_on', $order_on)->where('if_fz', 1)->update(['if_fz' => 2]);

            } elseif ($types == 4) {
                Db::name('customer_recharge_order')->where('order_on', $order_on)->where('if_fz', 1)->update(['if_fz' => 2]);
            }elseif ($types == 8) {
                Db::name('customer_coupon_order')->where('order_on', $order_on)->where('if_fz', 1)->update(['if_fz' => 2]);
            }

        }




    }

    /**
     * 微信分账
     * @param $room_id
     * @param $price1
     * @param $type
     * @param $content
     * @param $order_id
     * @param $status
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function distributions($room_id, $price1, $type, $content, $order_id, $status = 0)
    {
        $info = Db::name('mini_room_list_distribution')->where('store_id', $room_id)->find();


        if ($status > 0) {
            switch ($status) {
                case 1:
                    $order = Db::name('customer_order')->where('id', $order_id)->find();
                    $order['price'] = $order['pay_price'];
                    break;
                case 2:
                    $order = Db::name('customer_seat_order')->where('id', $order_id)->find();
                    $order['price'] = $order['price'] * 0.15;
                    break;
                case 3:
                    $order = Db::name('customer_recharge_order')->where('id', $order_id)->find();
                    break;
            }

        }
        $p = 0;
        $d['1_id'] = 0;
        $d['2_id'] = 0;
        $d['3_id'] = 0;
        if ($info) {
            if ($info['direct_id'] > 0) {
                $da1 = Db::name('mini_room_list')->where('id', $info['direct_id'])->where('mark', 1)->find();
                if ($da1) {
                    // 直推商家收益
                    $data['price'] = $price1 * 0.03;
                    $data['store_id'] = $da1['id'];
                    $data['direct_id'] = $room_id;
                    $data['type'] = $type;
                    $data['content'] = $content;
                    $data['order_id'] = $order_id;
                    Db::name('distribution_price')->insert($data);


                    $store = Db::name('customer_store_match')->where('store_id', $da1['id'])->find();
                    if ($store) {
                        $order['price'] = $data['price'];
                        $order['store_id'] = $da1['id'];
                        $this->SubLedger($order);
                    }

                    // 2级商家收益
                    if ($da1['direct_id'] > 0) {
                        $da2 = Db::name('mini_room_list')->where('id', $da1['direct_id'])->where('mark', 1)->find();

                        if ($da2['direct_num'] > 6) {

                            $data = array();
                            $d['2_id'] = $da2['id'];
                            $data['price'] = $price1 * 0.02;
                            $p = $p + 0.02;

                            $data['store_id'] = $da2['id'];
                            $data['direct_id'] = $room_id;
                            $data['second_id'] = $info['direct_id'];
                            $data['type'] = $type;
                            $data['content'] = $content;
                            $data['order_id'] = $order_id;
                            Db::name('distribution_price')->insert($data);

                            $store = Db::name('customer_store_match')->where('store_id', $da2['id'])->find();
                            if ($store) {
                                $order['price'] = $data['price'];
                                $order['store_id'] = $da2['id'];
                                $this->SubLedger($order);
                            }

                        }
                        // 3级商家收益
                        if ($da2['direct_id'] > 0) {
                            $da3 = Db::name('mini_room_list')->where('id', $da2['direct_id'])->where('mark', 1)->find();
                            if ($da3['direct_num'] > 6) {
                                // 查询2级商家推荐人数
                                $num = Db::name('mini_room_list')->where('direct_id', $da3['id'])->where('direct_num', '>', 14)->count();

                                if ($num > 1) {
                                    $num = $da3['direct_num'] + $da3['second_num'] + $da3['leve_num'];
                                    if ($num > 41) {
                                        $d['3_id'] = $da3['id'];
                                        $data = array();
                                        $p = $p + 0.01;
                                        $data['price'] = $price1 * 0.01;

                                        $data['store_id'] = $da3['id'];
                                        $data['direct_id'] = $room_id;
                                        $data['second_id'] = $da1['id'];
                                        $data['leve_id'] = $da2['id'];
                                        $data['type'] = $type;
                                        $data['content'] = $content;
                                        $data['order_id'] = $order_id;
                                        Db::name('distribution_price')->insert($data);


                                        $store = Db::name('customer_store_match')->where('store_id', $da3['id'])->find();
                                        if ($store) {
                                            $order['price'] = $data['price'];
                                            $order['store_id'] = $da2['id'];
                                            $this->SubLedger($order);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

            }

        }
        $info = Db::name('mini_room_list')->where('id', $room_id)->find();
        $da = Db::name('mini_room_list')->where('id', '<>', $room_id)->where('district_code', $info['district_code'])->where('is_long', 1)->find();
        if ($da) {
            $data = array();
            $data['price'] = $price1 * 0.01;
            $data['is_long'] = $da['id'];
            $data['direct_id'] = $room_id;
            $p = $p + 0.01;
            $data['type'] = $type;
            $data['content'] = $content;
            $data['order_id'] = $order_id;
            Db::name('distribution_price')->insert($data);


            $store = Db::name('customer_store_match')->where('store_id', $da['id'])->find();
            if ($store) {
                $order['price'] = $data['price'];
                $order['store_id'] = $da['id'];
                $this->SubLedger($order);
            }
        }
        // 更新商家金额

        $info = Db::name('mini_room_list')->where('id', $room_id)->find();
        if ($info['type'] < 3) {
            if ($info['type'] == 1) {
                $price = $price1 - ($price1 * 0.1);
            }
            if ($info['type'] == 2) {
                $price = $price1 - ($price1 * 0.3);
            }
            $store = Db::name('customer_store_match')->where('store_id', $room_id)->find();
            if ($store) {
                $order['price'] = $price;
                $order['store_id'] = $room_id;
                $this->SubLedger($order);
            }
        }

        $price = $price1 * (0.1 - $p);


        $da = array(
            'type' => $type,
            'content' => $content,
            'order_id' => $order_id,
            'store_id' => $room_id,
            'price' => $price,
            'create_time' => time(),
            'de_price' => $price1,
            'num' => 0.1 - $p,
            'level_id' => $d['3_id'],
            'second_id' => $d['2_id'],
            'direct_id' => $d['1_id'],

        );
        Db::name('admin_price')->insert($da);
    }


    /**
     * 付款到个人
     * @param $order
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function SubLedger($order)
    {

        $url = ' https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
        $wxapp = Db::name('mini_match')->where('id', 1)->find();
        $this->key = $wxapp['api_key'];
        $store = Db::name('customer_store_match')->where('store_id', $order['store_id'])->find();

        $data = array(
            'mch_appid' => $wxapp['app_id'], //小程序ID
            'mchid' => $wxapp['wc_hid'], //商户号
            'nonce_str' => $this->createNoncestr(), //随机字符串
            'partner_trade_no' => $order['order_on'],
            'openid' => $store['wc_hid'],
            'check_name' => 'NO_CHECK',
            'amount' => $order['price'],
            'desc' => '抽成',

        );
        $data['sign'] = $this->getSign($data);
        $result = $this->postXmlCurl($this->toXml($data), $url);

    }

    /**
     * 输出xml字符
     * @param $values
     * @return bool|string
     */
    private function toXml($values)
    {
        if (!is_array($values)
            || count($values) <= 0
        ) {
            return false;
        }

        $xml = "<xml>";
        foreach ($values as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    private static function postXmlCurl($xml, $url, $second = 30)
    {


        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //严格校验
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
        curl_setopt($ch, CURLOPT_TIMEOUT, 40);
        set_time_limit(0);
        //运行curl
        $data = curl_exec($ch);

        //返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            //throw new WxPayException("curl出错，错误码:$error");
        }
    }

    //作用：生成签名
    private function getSign($Obj)
    {
        foreach ($Obj as $k => $v) {
            $Parameters[$k] = $v;
        }


        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //签名步骤二：在string后加入KEY
        $String = $String . "&key=" . $this->key;
        //签名步骤三：MD5加密
        $String = md5($String);
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);

        return $result_;
    }

    //作用：产生随机字符串，不长于32位
    private function createNoncestr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 积分岑
     * @param $room_id
     * @param $price
     * @param $user_id
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function integral($room_id, $price, $user_id, $seat_id, $order_on)
    {

        $make = Db::name('coutomer_make')->where('store_id', $room_id)->find();
        if ($make) {
            if ($make['integral'] > 0) {
                $integral = $price * $make['integral'];
                $user = Db::name('member')->where('id', $user_id)->find();
                $us['integral'] = $user['integral'] + $integral;
                $data = array(
                    'integral' => $integral,
                    'before_integral' => $user['integral'],
                    'after_integral' => $us['integral'],
                    'store_id' => $integral,
                    'create_time' => time(),
                    'type' => 2,
                    'goods_id' => $seat_id,
                    'order_on' => $order_on,
                    'user_id' => $user_id,
                );
                if (Db::name('member')->where('id', $user_id)->update($us)) {
                    Db::name('mini_user_integral')->insert($data);
                }
            }
        }

    }

}